$(function() {
	var $deviceType = $("select[name='condition.deviceType']");
	var $deviceModel = $("select[name='condition.deviceModel']");
	var $allPicker = $("<input type='hidden' name='allPicker' value='true'/>");
	var $iconMsgTemplate = $("<div style='position: relative; padding-top: 5px;' id='iconMsg'><img  width='100px'  id='iconMsgImg' />"
			+ "<img  src='"
			+ path
			+ "/images/delete.png' id='iconDeleteImg' class='iconDeleteBtn' /></div>");

	var urlTemplate = "<div class='content' id='urlTemplate' >"
			+ "外部链接地址: <input type='hidden' name='bodyDtos[#index].type' value='URL'>"
			+ "<input type='text' name='bodyDtos[#index].value' class='noborder' readonly='readonly'> "
			+ "<input type='button' class='delUrl' value='删除'>" + "</div>"
	var imgTemplate = "<div class='content' id='imgTemplate' >"
			+ "<input type='hidden' name='bodyDtos[#index].type value='IMAGE'> "
			+ "<img src='#url' width='350px'  style='cursor: pointer;' />"
			+ "<img src='"
			+ path
			+ "/images/delete.png' class='uploadImgInfo' /> "
			+ "<input type='hidden' name='bodyDtos[#index].type' value='IMAGE'> "
			+ "<input type='hidden' name='bodyDtos[#index].value' />"
			+ "</div>";
	var txtTemplate = "<div class='content' id='textTemplate' >"
			+ "<input type='hidden' name='bodyDtos[#index].type' value='TXT' />"
			+ "<img src='" + path
			+ "/images/delete.png' class='deleteInfoBtn' />"
			+ "<textarea name='bodyDtos[#index].value' ></textarea>" + "</div>";

	var txtMessage = "<div id='text'><textarea  name='text' rows='6' cols='4'></textarea><input type='button' id='ok' value='确定' style='float:right;margin-right:1px;margin-top:5px'/></div>";
	var urlMessage = "<div id='url'><span style='font-size: 14px'>地址： </span><input type='text' name='link' value='' size='40'><input type='button' value='确定' id='ok'/></div>";
	var iconUploadMessage = "<div id='iconUpload'><form id='formIconUpload' method='post' enctype='multipart/form-data'><span style='font-size: 14px'>浏览图片： </span> <span id='updImgArea'><input id='fileIconUpload' name='fileMaterial' type='file' /> </span></form></div>";
	var uploadMessage = "<div id='upload'><form id='formUpload' method='post' enctype='multipart/form-data'><span style='font-size: 14px'>浏览图片： </span> <span id='updImgArea'><input id='fileUpload' name='fileMaterial' type='file' /> </span> 	<div id='message' style='font-size: 14px'></div></form>	</div>";

	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	$("input[name='condition.userName']").focus(function() {
		var $this = $(this);
		if ($this.val() == "昵称/用户名") {
			$this.val("");
		}
	}).blur(function() {
		var $this = $(this);
		if ($this.val() == "") {
			$this.val("昵称/用户名");
		}
	});
	var validOpts = {
		rules : {
			"pnsMessages.title" : {
				required : true,
				maxlength : 25
			},
			"pnsMessages.summary" : {
				required : true,
				maxlength : 50
			},
			"pnsMessages.startTime" : {
				required : true
			},
			"pnsMessages.expireTime" : {
				required : true
			}
		},
		messages : {
			"pnsMessages.title" : {
				required : "请填入标题",
				maxlength : "最大只能输入25个字符"
			},
			"pnsMessages.summary" : {
				required : "请填入简介",
				maxlength : "最大只能输入50个字符"
			},
			"pnsMessages.startTime" : {
				required : "请选择开始时间"
			},
			"pnsMessages.expireTime" : {
				required : "请选择结束时间"
			}
		},
		ignore : []
	};
	$("form#pnsAddForm").validate(validOpts);

	$(".uploadImgInfo,.deleteInfoBtn,.delUrl").click(function() {
		var $this = $(this);
		var $content = $this.parents(".content");
		var length = $(".contentAll").find(".content").length;
		if (length == 1) {
			alert("请至少保留一栏内容");
			return;
		}
		$content.remove();
	});
	$("#iconDeleteImg").click(function() {
		var $this = $(this);
		$this.parents("div#iconDiv").empty();
		$("input[name='pnsMessages.icon']").val("");
	});
	$deviceModel.dropdownchecklist({
		firstItemChecksAll : true,
		width : 200,
		maxDropHeight : 300
	});
	var resetBtn = function() {
		$("select[name='condition.deviceType']").get(0).selectedIndex = 0;
		$("select[name='condition.userType']").get(0).selectedIndex = 0;
		$("select[name='condition.provider']").get(0).selectedIndex = 0;
		$(".ui-dropdownchecklist span.ui-dropdownchecklist-text").text("");
		$("input[name='condition.deviceModel']").val("");
		$("input[name='condition.userName']").val("昵称/用户名");
		$("div.ui-dropdownchecklist-item").find(
				"input[type='checkbox']:checked").attr("checked", false);
	}
	var expandBtn = function() {
		var $this = $(this);
		var isExpand = $this.attr("class") == "yc" ? true : false;
		if (isExpand) {
			$this.removeClass("yc");
			$this.addClass("zk");
			$(".pagination").hide();
			$(".user_list").hide("slow");
			$("#pnsAdd").show();
		} else {
			$this.removeClass("zk");
			$this.addClass("yc");
			var params = {};
			var $addForm = $("form#pnsAddForm");
			if ($("#allPicker").attr("checked") == true) {
				params["allPicker"] = true
			} else {
				var checkedUser = $.unique($addForm.find(
						"input[name='ckUserBox'][type='hidden']").get());
				var checkUserArry = [];
				$.each(checkedUser, function(i) {
					checkUserArry.push($(this).val());
				});
				$.each($.unique(checkUserArry), function(i) {
					var value = checkUserArry[i];
					params["condition.userIds[" + i + "]"] = value;
				});
			}
			$.get(path + "/push/pnsSelectedListCount.action", params, function(
					msg) {
				initSelectedPagination(eval("(" + msg + ")"));
			});
		}
		return false;
	}
	var send = function() {
		var flag = false;
		var $chkUserBox = $("input[name='ckUserBox']");
		$chkUserBox.each(function() {
			if ($(this).attr("checked") == true) {
				flag = true;
			}
		});
		if (flag == false) {
			alert("请选择要发送的用户");
			return;
		}
		var $addForm = $("#pnsAdd");
		var $allPicker = $("input[name='allPicker']");
		if ($allPicker.attr("checked") == true) {
			$addForm
					.append("<input type='hidden' name='allPicker' value='true'/>");
		} else {
			var checkedUser = $.unique($("input[name='ckUserBox']:checked")
					.get());
			var checkUserArry = [];
			$.each(checkedUser, function(i) {
				checkUserArry.push($(this).val());
			});
			$.each($.unique(checkUserArry), function(i) {
				$addForm.append("<input type='hidden' name='ckUserBox' value='"
						+ checkUserArry[i] + "'/>");
			});
		}

		var $searchForm = $("#searchForm");
		$.each($searchForm.serializeArray(), function(i, field) {
			$addForm.append("<input type='hidden' name='" + field.name
					+ "' value='" + field.value + "'/>");
		});

		$("form#searchForm select,form#searchForm input").each(function() {
			var $this = $(this);
			$this.attr("disabled", "disabled");
		});
		$("form span.ui-dropdownchecklist-wrapper").unbind("click");
		$(".expand").show();
		$("#expand_btn").removeClass("yc");
		$("#expand_btn").addClass("zk");
		$(".user_list").hide("slow");
		$(".pagination").hide();
		$("#pnsAdd").show();
		$(".user_list").empty();
	}

	var initSelectedPagination = function(totalCount) {
		$("#pagination").empty();
		var pageCount;
		if (totalCount % 10 == 0) {
			pageCount = totalCount / 10;
		} else {
			pageCount = Math.floor(totalCount / 10) + 1;
		}
		$("#pagination").pagination(pageCount, {
			num_edge_entries : 1,
			num_display_entries : 4,
			callback : pageSelectedCallBack,
			items_per_page : 1,
			prev_text : "前一页",
			next_text : "后一页"
		});
	}
	var pageSelectedCallBack = function(page_index, jq) {
		var params = {};
		var $addForm = $("form#pnsAddForm");
		if ($("#allPicker").attr("checked") == true) {
			params["allPicker"] = true
		} else {
			var checkedUser = $.unique($addForm.find(
					"input[name='ckUserBox'][type='hidden']").get());
			var checkUserArry = [];
			$.each(checkedUser, function(i) {
				checkUserArry.push($(this).val());
			});
			$.each($.unique(checkUserArry), function(i) {
				var value = checkUserArry[i];
				params["condition.userIds[" + i + "]"] = value;
			});
		}
		params["pageNum"] = page_index + 1;
		params["pageSize"] = 10;
		$(".user_list").empty();
		$(".user_list").load(path + "/push/pnsSelectedList.action", params,
				function() {
					$(".user_list").show("slow", function() {
						$(".pagination").show();
						$("#pnsAdd").hide();
					});
				});
	}

	var initPagination = function() {
		var totalCount = $("input[name='initTotalCount']").val();
		var pageCount;
		if (totalCount % 10 == 0) {
			pageCount = totalCount / 10;
		} else {
			pageCount = Math.floor(totalCount / 10) + 1;
		}
		$("#pagination").pagination(pageCount, {
			num_edge_entries : 1,
			num_display_entries : 4,
			callback : pageCallback,
			items_per_page : 1,
			prev_text : "前一页",
			next_text : "后一页"
		});
	};
	var initPaginationBind = function($content) {
		$("#allPicker").click(function() {
			var flag = true;
			if ($("#allPicker").attr("checked") == true) {
				flag = true;
			} else {
				flag = false;
			}
			$("input[name='ckUserBox']").each(function() {
				$(this).attr("checked", flag);
			});
		});
		$("#send").click(send);
	};
	var pageCallback = function(page_index, jq) {
		var $searchForm = $("#searchForm");
		var params = {};
		$.each($searchForm.serializeArray(), function() {
			params[this.name] = this.value;
		});
		params["pageNum"] = page_index + 1;
		params["pageSize"] = 10;
		if ($("#allPicker").attr("checked") == true) {
			params["allPicker"] = true
		} else {
			var checkedUser = $.unique($("input[name='ckUserBox']:checked")
					.get());
			var checkUserArry = [];
			$.each(checkedUser, function(i) {
				checkUserArry.push($(this).val());
			});
			$.each($.unique(checkUserArry), function(i) {
				params["ckUserBox[" + i + "]"] = checkUserArry[i];
			});
		}
		$(".user_list").empty();
		$(".user_list").load(path + "/push/pnsList.action", params, function() {
			$(".pagination").show();
			initPaginationBind($(".user_list"));
		});

		return false;
	}
	var uploadClick = function() {
		var $uploadMessage = $(uploadMessage);
		var changeSuccFun = function(msg) {
			if (msg == "error") {
				alert("上传接口发生错误");
				return;
			}
			var $init = $(".contentAll #initTemplate");
			if ($init.length != 0) {
				var $input = $init.find("textarea");
				var $textVal = $input.val() == "" ? $input.text() : $input
						.val();
				if ($input.val() == "") {
					$init.remove();
				}
			}
			if ($(".contentAll").find("#urlTemplate").length > 0) {
				$(".contentAll").empty();
			}
			var length = $("div.contentAll div.content").length;
			var img = imgTemplate.replace(/#index/g, length);
			img = img.replace(/#url/g, msg);
			var $img = $(img);
			$(".contentAll").append($img);
			$img.find("[name$='.value']").val(msg.replace(serverUrl, ""));
			$img.find(".uploadImgInfo").click(function() {
				var length = $(".contentAll").find(".content").length;
				if (length == 1) {
					alert("请至少保留一栏内容");
					return;
				}
				$img.remove();
			});
			$.unblockUI();
		}

		var changeFun = function() {
			var $form = $uploadMessage.find("form#formUpload");
			var options = {
				url : path + '/push/upload.action',
				type : "POST",
				dataType : "text",
				async : false,
				success : changeSuccFun
			}
			$form.ajaxSubmit(options);
		}
		$.blockUI({
			theme : true,
			fadeIn : 1000,
			title : '添加图片',
			message : $uploadMessage,
		});
		$('.blockOverlay').attr('title', '点击关闭').click($.unblockUI);
		$uploadMessage.find("#fileUpload").change(changeFun);
	}
	var urlClick = function() {
		var isConfired = confirm("添加外部链接将清除以前添加的内容是否继续？");
		if (isConfired == false) {
			return;
		}
		var $urlMessage = $(urlMessage);

		var okClick = function() {
			var $linkVal = $urlMessage.find("input[name='link']").val();
			if ($linkVal == "") {
				alert("请填入地址");
				return;
			}
			if (isURL($linkVal) == false) {
				alert("请输入正确的URL地址");
				return;
			}
			$(".contentAll").empty();
			var index = $(".contentAll").find(".content").length;
			var $url = $(urlTemplate.replace(/#index/g, length));
			$(".contentAll").append($url);
			$url.find("[name$='.value']").val($linkVal);
			$url.find(".delUrl").click(function() {
				var length = $(".contentAll").find(".content").length;
				if (length == 1) {
					alert("请至少保留一栏内容");
					return;
				}
				$url.remove();
			});
			$.unblockUI();
		}
		$urlMessage.find("#ok").click(okClick);
		$.blockUI({
			theme : true,
			fadeIn : 1000,
			themedCSS : {
				width : "370px"
			},
			title : '添加外部链接',
			message : $urlMessage,
		});
		$('.blockOverlay').attr('title', '点击关闭').click($.unblockUI);

		function isURL(str_url) {
			var regExp = /(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i;
			if (str_url.match(regExp))
				return true;
			else
				return false;
		}
	}
	var textClick = function() {
		var $txtMessage = $(txtMessage);
		var okClick = function() {
			var $textInput = $txtMessage.find("textarea[name='text']");
			var $textVal = $textInput.val() == "" ? $textInput.text()
					: $textInput.val();
			if ($textVal == "") {
				alert("请填入内容");
				return;
			}
			var length = $(".contentAll").find(".content").length;
			var txt = txtTemplate.replace(/#index/g, length);
			var $txt = $(txt);
			if ($(".contentAll").find("#urlTemplate").length > 0) {
				$(".contentAll").empty();
			}
			$(".contentAll").append($txt);
			$txt.find("[name$='.value']").val($textVal).attr("readlonly",
					"readonly");
			$txt.find("textarea").rules("add", {
				required : true,
				messages : {
					required : "也是必填"
				}
			});
			$txt.find(".deleteInfoBtn").click(function() {
				var length = $(".contentAll").find(".content").length;
				if (length == 1) {
					alert("请至少保留一栏内容");
					return;
				}
				$txt.remove();
			});
			$txt.find("textarea").attr("readonly", "readonly");
			$.unblockUI();
		}
		$txtMessage.find("#ok").click(okClick);
		$.blockUI({
			theme : true,
			fadeIn : 1000,
			title : '添加文本内容',
			themedCSS : {
				width : "370px"
			},
			message : $txtMessage,
		});
		$('.blockOverlay').attr('title', '点击关闭').click($.unblockUI);
	}
	var iconUploadClick = function() {
		var $iconUploadMessage = $(iconUploadMessage);
		var changeSuccFun = function(msg) {
			if (msg == "error") {
				alert("上传接口发生错误");
				return;
			}
			$("#iconUpload").dialog("close");
			$("input[name='pnsMessages.icon']").val(msg);
			var $iconDiv = $("#iconDiv");
			$iconDiv.empty();
			var $iconMsgTemplateC = $iconMsgTemplate.clone();
			$iconDiv.append($iconMsgTemplateC);
			$iconMsgTemplateC.find("#iconDeleteImg").click(function() {
				$iconDiv.empty();
				$(this).remove();
				$("input[name='pnsMessages.icon']").val("");
			});
			$("#iconMsgImg").attr("src", msg);
			$.unblockUI();
		}
		var changeFun = function() {
			var $form = $iconUploadMessage.find("form#formIconUpload");
			var options = {
				url : path + '/push/upload.action',
				type : "POST",
				dataType : "text",
				async : false,
				success : changeSuccFun
			};
			$form.ajaxSubmit(options);
		}
		$iconUploadMessage.find("#fileIconUpload").change(changeFun);
		$.blockUI({
			theme : true,
			fadeIn : 1000,
			title : '添加图标',
			message : $iconUploadMessage,
		});
		$('.blockOverlay').attr('title', '点击关闭').click($.unblockUI);
	}
	$("#iconUploadBtn").click(iconUploadClick);
	$(".icon_tjwb").click(textClick);
	$(".icon_tjwblj").click(urlClick);
	$(".icon_tjtp").click(uploadClick);

	$("#expand_btn").click(expandBtn);
	$("#restBtn").click(resetBtn);
	$.blockUI.defaults.themedCSS = {
		width : '350px',
		top : '40%',
		left : '35%'
	}
	if (toDo == "add") {
		initPagination();
	} else {
		$("#pnsAdd").show();
	}
});
function sub(form) {
	var $form = $(form);
	var length = $(".contentAll").find(".content").length;
	if (length == 0) {
		alert("请添加发送内容");
		return false;
	}
	if (!$form.valid()) {
		return false;
	}
	return true;
}
